package com.example.myblog.interceptor;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: mySringMVC
 * @BelongsPackage: com.example.mysringmvc.interceptior
 * @ClassName MyInterceptor
 * @CreateTime: 2025-05-15  16:29
 * @Author: TangLiFei
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         System.out.println("拦截器处理请求: " + request.getRequestURI());
         Object obj=request.getSession().getAttribute("user");
         if(obj!=null){
             System.out.println("用户已登录，放行请求");
             return true;
         }
         System.out.println("用户未登录，重定向到登录页");
         request.setAttribute("msg","请登录");
         request.getRequestDispatcher("/").forward(request,response);
         return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //System.out.println("postHandle**************");
     }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //System.out.println("afterCompletion**************");
    }
}
